import sys
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtCore import Qt

class StockWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        # 设置窗口图标
        self.setWindowIcon(QtGui.QIcon('../app.png'))  # 使用上级目录的ico文件
        self.init_ui()
        self.load_data()
        
    def init_ui(self):
        # 窗口基础设置
        self.setGeometry(300, 300, 1000, 700)
        self.setWindowTitle("上证指数K线图")  # 移除了"- 专业版"后缀
        
        # 主场景和视图
        self.scene = QtWidgets.QGraphicsScene()
        self.view = QtWidgets.QGraphicsView(self.scene)
        self.setCentralWidget(self.view)
        
        # 视图样式调整（浅色系）
        self.view.setStyleSheet("""
            background: #E0E0E0;
            border: 1px solid #A0A0A0;
        """)
        
        # 视图样式设置
        self.view.setStyleSheet("background: #1A1A1A; border: 1px solid #404040;")
        self.view.setRenderHint(QtGui.QPainter.Antialiasing)
        
        # 坐标变换系统 (核心修复)
        transform = QtGui.QTransform()
        transform.scale(1, -1)  # Y轴翻转
        transform.translate(0, -600)  # 垂直位移补偿
        self.view.setTransform(transform)
        
        # 操作提示面板
        self.create_info_panel()
        
    def create_info_panel(self):
        self.info_label = QtWidgets.QLabel(
            "操作指南：↑放大  ↓缩小  ←左移  →右移",
            self.view
        )
        self.info_label.setStyleSheet("""
            QLabel {
                background: rgba(230,230,230,220);
                color: #0000FF;
                padding: 12px;
                border-radius: 6px;
                font: bold 16px Arial;
                min-width: 320px;
                min-height: 50px;
                /* 新增以下两个属性 */
                qproperty-alignment: AlignCenter; /* 文字居中 */
                border: 1px solid rgba(200,200,200,150); /* 增加边框增强可见性 */
            }
        """)
        self.info_label.raise_()  # 新增这行确保在最顶层显示
        self.info_label.setGeometry(20, 20, 320, 50)  # 调整尺寸

    def load_data(self):  # 添加缺失的方法
        try:
            import akshare as ak
            df = ak.stock_zh_index_daily(symbol="sh000001")
            df = df.reset_index()[['date', 'open', 'high', 'low', 'close']]
            df = df.sort_values('date').tail(200)
            self.chart_data = df.to_dict('records')
        except Exception as e:
            print("数据获取失败，使用测试数据:", e)
            self.chart_data = [{
                'open': 3000 + i + 10*(-1)**i,
                'high': 3020 + i + 5*(-1)**i,
                'low': 2980 + i - 5*(-1)**i,
                'close': 3010 + i + 10*(-1)**i
            } for i in range(200)]
        self.draw_chart()

    def draw_chart(self):  # 补充绘图方法
        self.scene.clear()
        item = CandleItem(self.chart_data)
        self.scene.addItem(item)
        self.view.fitInView(item.boundingRect(), Qt.KeepAspectRatio)
        self.view.scale(6,6)

class CandleItem(QtWidgets.QGraphicsItem):
    def __init__(self, data):
        super().__init__()
        self.data = data
        self.candle_width = 8
        self.min = min(d['low'] for d in data)
        self.max = max(d['high'] for d in data)
        self.range = self.max - self.min if self.max != self.min else 1
        
    def boundingRect(self):
        return QtCore.QRectF(0, 0, 
                            (len(self.data)+2.5)*self.candle_width,  # 右侧多留2.5个蜡烛图宽度（约20px）
                            600)

    def paint(self, painter, option, widget):
        # 价格映射函数
        def map_price(p):
            return ((p - self.min) / self.range) * 600  # 600为绘图区高度
            
        # 绘制每个K线
        for i, d in enumerate(self.data):
            x = i * self.candle_width
            high = map_price(d['high'])
            low = map_price(d['low'])
            open = map_price(d['open'])
            close = map_price(d['close'])
            
            # 绘制影线
            painter.setPen(QtGui.QPen(QtGui.QColor(100,100,100), 1))
            mid_x = x + self.candle_width/2
            painter.drawLine(mid_x, high, mid_x, low)
            
            # 绘制实体
            color = QtGui.QColor(239, 83, 80) if close > open else QtGui.QColor(38, 166, 91)
            painter.setBrush(color)
            painter.setPen(Qt.NoPen)
            
            body_top = max(open, close)
            body_height = abs(open - close)
            if body_height < 1:  # 处理极窄实体
                body_height = 1
                body_top = open - 0.5
                
            painter.drawRect(x, body_top, 
                            self.candle_width, body_height)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    window = StockWindow()
    window.show()
    sys.exit(app.exec_())
